import { reactive, ref } from 'vue'
import { createArticle, deleteArticle, fetchArticleDetail, fetchArticleList, updateArticle } from '@/services/api'
import { Toast } from '@/utils/uniapi/prompt'

export function useArticleData() {
  const loading = ref(false)

  const query = reactive({
    categoryNum: '', // 类别编号
    startDate: '', // 开始日期
    endDate: '', // 结束日期
    overdate: '', // 过期日期
    keyword: '', // 关键词
    top: 0, // 指定前几条, 大于0时有效
    page: 1, // 当前页数
    pageSize: 20, // 每页值
  })

  const pageList = ref<ApiModels.PageList<ApiModels.base.Article>>({
    list: [],
    page: 1,
    totalPageCount: 0,
    totalItemCount: 0,
  })

  /**
   * 获取详情
   * @param id id
   */
  const getDetail = async (id: string) => {
    const res = await fetchArticleDetail(id)
    return res.error ? null : res.data
  }

  /**
   * 获取列表
   * @param page 页码
   */
  const fetchList = async (page: number | undefined = undefined, pageSize: number | undefined = undefined) => {
    page && (query.page = page)
    pageSize && (query.pageSize = pageSize)
    loading.value = true
    const res = await fetchArticleList({ ...query })
    if (!res.error) {
      pageList.value = res.data
      loading.value = false
    }
  }

  // 修改页数
  const changePage = async (page: number) => {
    await fetchList(page)
  }

  // 修改分页大小
  const changePageSize = async (pageSize: number) => {
    query.pageSize = pageSize
    await fetchList(1)
  }

  // * 创建资讯
  const create = async (data: ApiModels.base.Article) => {
    const res = await createArticle(data)
    if (res.error) {
      Toast(res.error.msg || '服务端异常')
      return res
    }
    Toast('成功创建')
    await fetchList(1)
    return res
  }

  // * 更新资讯
  const update = async (data: ApiModels.base.Article) => {
    const res = await updateArticle(data)
    if (!res.error) {
      Toast('成功更新')
      const index = pageList.value.list.findIndex(i => i.id === data.id)
      index >= 0 && pageList.value.list.splice(index, 1, res.data)
    }
    return res
  }

  // * 删除资讯
  const remove = async (id: string) => {
    const res = await deleteArticle(id)
    if (res.error) {
      Toast(res.error.msg || '服务端异常')
      return res
    }
    const index = pageList.value.list.findIndex(i => i.id === id)
    index >= 0 && pageList.value.list.splice(index, 1)
    return res
  }

  return {
    loading,
    query,
    pageList,
    getDetail,
    fetchList,
    changePage,
    changePageSize,
    create,
    update,
    remove,
  }
}
